import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;

import weka.classifiers.AbstractClassifier;
import weka.core.Attribute;
import weka.core.Instances;

public class Helpers {

	// see
	// http://weka.wikispaces.com/Use+WEKA+in+your+Java+code#Classification-Classifying%20instances
	public static Instances ClassifyInstances(
			final AbstractClassifier classify, final Instances unlabeled)
			throws Exception {
		final Instances labeled = new Instances(unlabeled);
		labeled.insertAttributeAt(new Attribute("Anomaly"),
				labeled.numAttributes());
		labeled.setClassIndex(labeled.numAttributes() - 1);
		for (int x = 0; x < unlabeled.numInstances(); x++)
			labeled.instance(x).setClassValue(
					classify.classifyInstance(unlabeled.instance(x)));
		return labeled;
	}

	public static String cleanAnomalousDataFromCSV(final String inName) {

		final String outName = inName.subSequence(0, inName.length() - 4)
				+ "_AnomalyClean.arff";
		FileWriter fw;

		try {

			final File f = new File(outName);
			if (f.exists())
				f.delete();

			final BufferedReader br = new BufferedReader(new FileReader(inName));
			fw = new FileWriter(outName);

			final String[] attr = br.readLine().split(",");
			fw.write("@RELATION DATA\n");
			for (final String element : attr)
				fw.write("@ATTRIBUTE " + element + " NUMERIC\n");
			fw.write("@DATA\n");
			while (br.ready()) {
				final String line = br.readLine();
				if (line.charAt(0) == '0')
					fw.write(line + "\n");
			}

			br.close();
			fw.close();

		} catch (final Exception e) {
			System.exit(1);
		}

		return outName;
	}

	/**
	 * converts csv to arff
	 */
	public static String csvToArff(final String inName) {

		final String outName = inName.subSequence(0, inName.length() - 3)
				+ "arff";
		FileWriter fw;

		try {

			final File f = new File(outName);
			if (f.exists())
				f.delete();

			final BufferedReader br = new BufferedReader(new FileReader(inName));
			fw = new FileWriter(outName);

			final String[] attr = br.readLine().split(",");
			fw.write("@RELATION DATA\n");
			for (final String element : attr)
				fw.write("@ATTRIBUTE " + element + " NUMERIC\n");
			fw.write("@DATA\n");
			while (br.ready())
				fw.write(br.readLine() + "\n");

			br.close();
			fw.close();

		} catch (final Exception e) {
			System.exit(1);
		}

		return outName;
	}
}
